package com.example.demo.service.impl;

import com.example.demo.bean.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.jwt.ResultCode;
import com.example.demo.common.PageResult;
import com.example.demo.common.UserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userMapper.findByUsername(username);
        if (user != null) {
            user.setUpwd(null); // 安全考虑，清除密码
        }
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.findAll();
        users.forEach(user -> user.setUpwd(null));
        return users;
    }

    @Override
    @Transactional
    public User updateUser(User user) {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("未登录");
        }

        // 只有管理员可以修改角色
        if (!UserRole.ADMIN.getValue().equals(currentUser.getRole())) {
            user.setRole(currentUser.getRole());  // 保持原有角色不变
        }

        // 如果是普通用户，只能修改自己的信息
        if (UserRole.USER.getValue().equals(currentUser.getRole()) 
            && !currentUser.getId().equals(user.getId())) {
            throw new RuntimeException("无权修改其他用户信息");
        }

        userMapper.update(user);
        user.setUpwd(null);  // 清除密码信息
        return user;
    }

    @Override
    @Transactional
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public List<User> getUsersByClass(String className) {
        List<User> users = userMapper.findByClass(className);
        users.forEach(user -> user.setUpwd(null));
        return users;
    }

    @Override
    public User getUserById(Integer id) {
        User user = userMapper.findById(id);
        if (user != null) {
            user.setUpwd(null);
        }
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            user.setUpwd(null);
        }
        return user;
    }

    @Override
    public PageResult<User> getUsersByPage(int pageNum, int pageSize, String search) {
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        log.debug("开始分页查询: offset={}, pageSize={}, search={}", offset, pageSize, search);
        
        // 查询数据
        List<User> users = userMapper.findByPage(offset, pageSize, search);
        log.debug("查询到的用户数量: {}", users != null ? users.size() : 0);
        
        // 查询总数
        long total = userMapper.countTotal(search);
        log.debug("总记录数: {}", total);
        
        // 处理敏感信息
        if (users != null) {
            users.forEach(user -> user.setUpwd(null));
        }
        
        PageResult<User> result = new PageResult<>(users, total, pageNum, pageSize);
        log.debug("返回的分页结果: {}", result);
        
        return result;
    }
} 